package com.gogowan.agroenterprise.newview;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.PaiMaTypeMoreActivity;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.GreenHoseResultInfo;
import com.gogowan.agroenterprise.model.GreenhousesModel;
import com.gogowan.agroenterprise.model.GreenhousesRequest;
import com.gogowan.agroenterprise.model.GreenhousesResult;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.MaBatchModel;
import com.gogowan.agroenterprise.model.MaterialModel;
import com.gogowan.agroenterprise.model.NcpFile;
import com.gogowan.agroenterprise.model.NcpRequestInfo;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.VideoInfo;
import com.gogowan.agroenterprise.utils.SystemBroadCast;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.OperationPicturesGridView;
import com.gogowan.agroenterprise.widget.OperationVideoGridView;

/**
 * @author tjh 2017-03-30
 * @功能 巡检信息
 * @描述 当拍摄图片和视频后，先上传至ftp服务器，然后将文件名数组上传
 */
public class NewSpectorActivity extends BaseActivity implements OnClickListener {
	private ProgressDialog progressDialog;
	private TextView picNewsTextView, vioNewsTextView;
	private OperationPicturesGridView picGrid;
	private OperationVideoGridView videoGrid;
	private String[] list = null;
	private List<NcpFile> ncpFiles;

	private Spinner scdySprinner, cpSprinner, pcSprinnner;
	private EditText xjjgEdit;
	private TextView czrText, sjText;

	// / 生产基地列表
	private List<GreenhousesModel> greenhousesList = new ArrayList<GreenhousesModel>();
	private List<String> greenhousesStrList = new ArrayList<String>();
	private ArrayAdapter<String> greenhousesAdapter;
	// /产品列表
	private List<MaterialModel> materialList = new ArrayList<MaterialModel>();
	private List<String> materialStrList = new ArrayList<String>();
	private ArrayAdapter<String> materialAdapter;
	// / 获取批次列表
	private List<MaBatchModel> maBatchList = new ArrayList<MaBatchModel>();
	private List<MaBatchModel> maBatchChildList = new ArrayList<MaBatchModel>();
	private List<String> maBatchChildStrList = new ArrayList<String>();
	private ArrayAdapter<String> maBatchAdapter;

	
	private long enterpriseid;
	// / 生产基地ID
	private long greenHouseID;
	// / 批次名称
	private String batchName;
	private long materialID;

	// 上传网址
	private String domainName = null;
	// FTP用户名
	private String name = null;
	// FTP密码
	private String pwd = null;
	private FTPClient ftp;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				Log.i("mylog", "请求结果为-->" + "0000000000000000000");
				break;
			case 1:
				greenhousesAdapter.notifyDataSetChanged();
				materialAdapter.notifyDataSetChanged();
				break;
			case 2:
				maBatchAdapter.notifyDataSetChanged();
				if (maBatchChildStrList.size() > 0) {
					batchName = maBatchChildStrList.get(0);
				}
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.new_spector_activity);

		initView();
		initValue();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		scdySprinner = (Spinner) findViewById(R.id.new_spector_scdy_text);
		cpSprinner = (Spinner) findViewById(R.id.new_spector_cpmc_edit);
		pcSprinnner = (Spinner) findViewById(R.id.new_spector_pc_edit);
		// / 生产基地列表
		greenhousesAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, greenhousesStrList) {

			@Override
			public View getDropDownView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
				TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
				ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
				label.setText(greenhousesStrList.get(position));
				if (scdySprinner.getSelectedItemPosition() == position) {
					check.setImageResource(R.drawable.invent_select);
					// viewHolder.selectBtn.setVisibility(View.GONE);
				} else {
					check.setImageResource(R.drawable.invent_noselect);
				}
				return view;
			}
		};
		greenhousesAdapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
		scdySprinner.setAdapter(greenhousesAdapter);

		// /产品列表
		materialAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, materialStrList) {

			@Override
			public View getDropDownView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
				TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
				ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
				label.setText(materialStrList.get(position));
				if (cpSprinner.getSelectedItemPosition() == position) {
					check.setImageResource(R.drawable.invent_select);
					// viewHolder.selectBtn.setVisibility(View.GONE);
				} else {
					check.setImageResource(R.drawable.invent_noselect);
				}
				return view;
			}
		};
		materialAdapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
		cpSprinner.setAdapter(materialAdapter);

		// / 获取批次列表
		maBatchAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, maBatchChildStrList) {

			@Override
			public View getDropDownView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
				TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
				ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
				label.setText(maBatchChildStrList.get(position));
				if (pcSprinnner.getSelectedItemPosition() == position) {
					check.setImageResource(R.drawable.invent_select);
					// viewHolder.selectBtn.setVisibility(View.GONE);
				} else {
					check.setImageResource(R.drawable.invent_noselect);
				}
				return view;
			}
		};
		maBatchAdapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
		pcSprinnner.setAdapter(maBatchAdapter);
		// 生产单元
		scdySprinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				greenHouseID = greenhousesList.get(position).getGreenhouses_ID();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		// 产品
		cpSprinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				materialID = materialList.get(position).getMaterial_ID();
				maBatchChildList.clear();
				maBatchChildStrList.clear();
				for (int i = 0; i < maBatchList.size(); i++) {
					if (maBatchList.get(i).getMaterial_ID() == materialID) {
						maBatchChildList.add(maBatchList.get(i));
						maBatchChildStrList.add(maBatchList.get(i).getBatchName());
					}
				}
				handler.sendEmptyMessage(2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		// 批次
		pcSprinnner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				batchName = maBatchChildStrList.get(position);
				Log.e("pcpcpcpccpp=========", "pcpcpcpccpp=========");
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		// 图片选择
		picNewsTextView = (TextView) findViewById(R.id.new_spector_pic_news);
		picGrid = (OperationPicturesGridView) findViewById(R.id.new_spector_pic_grid);
		picGrid.setLisenter(NewSpectorActivity.this);
		// 视频选择
		vioNewsTextView = (TextView) findViewById(R.id.new_spector_vio_news);
		videoGrid = (OperationVideoGridView) findViewById(R.id.new_spector_video_grid);
		videoGrid.setOperation(NewSpectorActivity.this);

		czrText = (TextView) findViewById(R.id.new_spector_czr_text);
		xjjgEdit = (EditText) findViewById(R.id.new_spector_xjjg_edit);
		sjText = (TextView) findViewById(R.id.new_spector_sj_text);
		sjText.setOnClickListener(this);

		// 返回
		findViewById(R.id.new_spector_backBtn).setOnClickListener(this);
		// 拍照
		findViewById(R.id.new_spector_paizhao_imageView).setOnClickListener(this);
		// 摄像
		findViewById(R.id.new_spector_shexiang_imageView).setOnClickListener(this);
		// 生产单元扫码
		findViewById(R.id.new_spector_scdysm_btn).setOnClickListener(this);
		// 保存提交
		findViewById(R.id.new_spector_bctj_btn).setOnClickListener(this);
		// 取消
		findViewById(R.id.new_spector_qx_btn).setOnClickListener(this);
		initScanView(new SystemBroadCast.ScanResultListener() {
			@Override
			public void OnResult(String CodeString) {
				if (isVisible){
					xiaobangScan(CodeString);
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {
		SharedPreferences preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		
		
		czrText.setText(MyApplication.mSettings.getString("username",""));
		//enterpriseid = loginResultInfo.getEnterpriseinfo().getEnterpriseid();

		// 上传网址
		//domainName = loginResultInfo.getFtpulr();
		// FTP用户名
		//name = loginResultInfo.getFtpusername();
		// FTP密码
		//pwd = loginResultInfo.getFtppwd();
		Log.e("ftp================", domainName + "===" + name + "===" + pwd);

		progressDialog = ProgressDialog.show(this, "提示", "正在获取信息....", true, false);

		GreenhousesRequest greenhousesRequest = new GreenhousesRequest();
		greenhousesRequest.setEnterpriseID(enterpriseid);

		GetAllBaseInfoAsyn getAllBaseInfoAsyn = new GetAllBaseInfoAsyn();
		getAllBaseInfoAsyn.execute(greenhousesRequest);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.new_spector_backBtn:
			// 返回
			this.finish();
			break;
		case R.id.new_spector_paizhao_imageView:
			// 拍照
			// 开启线程 创建FTPClient对象
			new Thread(runnable).start();
			Intent intent = new Intent(this, PaiMaTypeMoreActivity.class);
			intent.putExtra("type", 2);
			startActivityForResult(intent, 10);
			break;
		case R.id.new_spector_shexiang_imageView:
			// 摄像
			// 开启线程 创建FTPClient对象
			new Thread(runnable).start();
			Intent intent3 = new Intent(this, PaiMaTypeMoreActivity.class);
			intent3.putExtra("type", 3);
			startActivityForResult(intent3, 20);
			break;
		case R.id.new_spector_scdysm_btn:
			// 生产单元扫码
			Intent intent2 = new Intent(Intents.Scan.ACTION);
			startActivityForResult(intent2, 100);
			break;
		case R.id.new_spector_sj_text:
			// 时间
			ShowDateDialog("", new Handler.Callback() {

				@Override
				public boolean handleMessage(Message msg) {
					// TODO Auto-generated method stub
					sjText.setText(msg.getData().getString("token"));
					return false;
				}
			});
			break;
		case R.id.new_spector_bctj_btn:
			// 保存提交
			if (Utils.isEmpty(xjjgEdit.getText() + "")) {
				showToast("请输入描述巡检结果信息");
			} else if (maBatchChildStrList.size() == 0) {
				showToast("未找到该产品的生成码记录！");
			} else if ((sjText.getText() + "").equals("点击设置时间")) {
				showToast("请设置时间");
			} else {
				progressDialog = ProgressDialog.show(this, "提示", "正在提交数据....", true, false);
				NcpRequestInfo ncpRequestInfo = new NcpRequestInfo();
				ncpRequestInfo.setEnterpriseid(enterpriseid);
				ncpRequestInfo.setNcpcontent(xjjgEdit.getText() + "");
				ncpRequestInfo.setUsername(MyApplication.mSettings.getString("username",""));
				//ncpRequestInfo.setUsercode(loginResultInfo.getUserinfo().getUsercodenum());
//				ncpRequestInfo.setFtpFile(loginResultInfo.getFtpfile());

				try {
					List<PicturesInfo> picInfos = picGrid.getList();
					List<VideoInfo> videoInfos = videoGrid.getList();

					ncpFiles = new ArrayList<NcpFile>();
					if ((picInfos == null || picInfos.size() == 0) && (videoInfos == null || videoInfos.size() == 0)) {
						ncpRequestInfo.setNcpfilearr(null);
					} else {
						if (picInfos != null && picInfos.size() != 0) {
							for (int i = 0; i < picInfos.size(); i++) {
								NcpFile ncpFile = new NcpFile();
								ncpFile.setFiledir(picInfos.get(i).getPureName());
								ncpFile.setFiletype(1);
								ncpFile.setFiledescriptions(picInfos.get(i).getDescription());
								ncpFiles.add(ncpFile);
							}
						}

						if (videoInfos != null && videoInfos.size() != 0) {
							for (int i = 0; i < videoInfos.size(); i++) {
								NcpFile ncpFile = new NcpFile();
								ncpFile.setFiledir(videoInfos.get(i).getVideourl());
								ncpFile.setPicdir(videoInfos.get(i).getImageurl());
								ncpFile.setFiletype(2);
								ncpFile.setFiledescriptions(videoInfos.get(i).getDescription());
								ncpFiles.add(ncpFile);
							}
						}
						NcpFile[] resources = new NcpFile[ncpFiles.size()];
						for (int i = 0; i < ncpFiles.size(); i++) {
							resources[i] = ncpFiles.get(i);
						}
						ncpRequestInfo.setNcpfilearr(resources);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				ncpRequestInfo.setIsnew(MyApplication.mSettings.getBoolean("isNew",false));
				ncpRequestInfo.setPersonid(MyApplication.mSettings.getLong("personid",0));
				ncpRequestInfo.setGreenHouseID(greenHouseID);
				ncpRequestInfo.setBatchName(batchName);
				ncpRequestInfo.setOperateDate(sjText.getText() + "");

				SaveDateAsyn saveDateAsyn = new SaveDateAsyn();
				saveDateAsyn.execute(ncpRequestInfo);
			}
			break;
		case R.id.new_spector_qx_btn:
			// 取消
			this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 10) {
			// 上传图片返回
			if (resultCode == 1) {
				// 拍照
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				image2SDcard(intent);
				NewSpectorActivity.this.startActivityForResult(intent, 0);
			} else if (resultCode == 2) {
				// 选择照片
				Intent intent;
				if (Build.VERSION.SDK_INT < 19) {
					intent = new Intent(Intent.ACTION_GET_CONTENT);
					intent.setType("image/*");
				} else {
					intent = new Intent(Intent.ACTION_PICK,
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				}
				NewSpectorActivity.this.startActivityForResult(intent, 1);
			}
		} else if (requestCode == 20) {
			if (resultCode == 1) {
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
				this.startActivityForResult(intent, 2);
			} else if (resultCode == 2) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("video/*");
				this.startActivityForResult(intent, 3);
			}
		} else if (resultCode == RESULT_OK) {
			if (requestCode == 0 || requestCode == 1) {
				// 拍照或选择照片回传的数据
				picGrid.onViewResult(requestCode, resultCode, data, 1, 1, ftp, list);
			} else if (requestCode == 2 || requestCode == 3) {
				// 拍摄视频或选择视频回传的数据
				if (videoGrid.isTypeOk(data)) {
					Uri originalUri = data.getData(); // 获得图片的uri
					// 无论是本地的视频还是系统拍摄的视频地址都是媒体库中的地址
					String path = Utils.getImageAbsolutePath(this, originalUri);
					long size = 0;
					try {
						size = Utils.getFileSize(new File(path));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (size >= 5242880) {
						Toast.makeText(this, "视频文件不能超过5M", Toast.LENGTH_LONG).show();
					} else {
						videoGrid.onViewResult(requestCode, resultCode, data, ftp);
						vioNewsTextView.setVisibility(View.VISIBLE);
						videoGrid.setVisibility(View.VISIBLE);
					}

				} else {
					Toast.makeText(this, "暂不支持此格式文件上传", Toast.LENGTH_LONG).show();
				}
			} else if (requestCode == 100) {
				// 生成单元
				// Spinner.setText(data.getStringExtra("SCAN_RESULT").trim());
				progressDialog = ProgressDialog.show(this, "提示", "正在提交数据....", true, false);

				CodeActivationInfo codeActivationInfo = new CodeActivationInfo();
				codeActivationInfo.setStartcode(data.getStringExtra("SCAN_RESULT").trim());
				codeActivationInfo.setEnterpriseid(enterpriseid);
				codeActivationInfo.setIsnew(MyApplication.mSettings.getBoolean("isNew",false));

				GetSCJDInfoAsyn getSCJDInfoAsyn = new GetSCJDInfoAsyn();
				getSCJDInfoAsyn.execute(codeActivationInfo);
			}
		}
	}

	// 展示图片
	public void showView() {
		picGrid.setVisibility(View.VISIBLE);
		picNewsTextView.setVisibility(View.VISIBLE);
	}

	// 隐藏图片
	public void hideView() {
		picGrid.setVisibility(View.GONE);
		picNewsTextView.setVisibility(View.GONE);
	}

	private void image2SDcard(Intent intent) {
		File sdDir;
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Toast.makeText(NewSpectorActivity.this, "无SD卡", Toast.LENGTH_SHORT).show();
			return;
		} else {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}

		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		File file = new File(sdDir.getPath() + "/AgricultureSystem/Image/");
		file.mkdirs();// 创建文件夹
		String dataStr = formatter.format(date);
		String newCapturePhotoPath = null;

		newCapturePhotoPath = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N?sdDir.getAbsolutePath():sdDir.getPath()) + "/Image/" + dataStr + ".jpg";;

		String name = newCapturePhotoPath;

		picGrid.setName(name);
		picGrid.setNewCapturePhotoPath(newCapturePhotoPath);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			//添加这一句表示对目标应用临时授权该Uri所代表的文件
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			//通过FileProvider创建一个content类型的Uri
			File imagefile = new File(newCapturePhotoPath);
			Uri uri = FileProvider.getUriForFile(this, "downxml", imagefile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		} else {
			Uri uri = Uri.fromFile(new File(newCapturePhotoPath));
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		}
	}

	// FTP线程
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			ftp = new FTPClient();
			ftp.setCharset("utf-8");
			ftp.setType(FTPClient.TYPE_BINARY);
			try {
				URL url = new URL(domainName.trim());
				// int port = url.getPort() < 1 ? 21 : url.getPort();
				Log.i("Ftp server listening on address============= ", url.toString());
				ftp.connect(url.getHost());
				ftp.login(name.trim(), pwd.trim());

				String path = url.getPath();
//				if (!TextUtils.isEmpty(path) && !path.equals("/")) {
//					if (isExist(path + loginResultInfo.getFtpfile().trim())) {
//						// ftp.changeDirectory("cp/"+loginResultInfo.getFtpfile());
//					} else {
//						ftp.changeDirectory(path);
//						// 不存在该目录，则创建目录
//						ftp.createDirectory(loginResultInfo.getFtpfile());
//						ftp.changeDirectory(loginResultInfo.getFtpfile());
//					}
//				} else {
//					ftp.changeDirectory(loginResultInfo.getFtpfile());
//				}

			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPIllegalReplyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.sendEmptyMessage(0);
		}
	};

	public boolean isExist(String dir) {
		try {
			ftp.changeDirectory(dir);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 获取生产基地列表接口类
	 * 
	 * @author tjh
	 */
	private class GetAllBaseInfoAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {

			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
				} else {
					GreenhousesResult resultInfo = (GreenhousesResult) Utils.fromJSON(string, GreenhousesResult.class);
					int result = resultInfo.getResult();
					if (result == 16000) {
						// / 生产基地列表
						if (resultInfo.getGreenhousesList() != null) {
							greenhousesList.addAll(resultInfo.getGreenhousesList());
							for (int i = 0; i < greenhousesList.size(); i++) {
								greenhousesStrList.add(greenhousesList.get(i).getGreenhousesName());
							}
						}
						// /产品列表
						if (resultInfo.getMaterialList() != null) {
							materialList.addAll(resultInfo.getMaterialList());
							for (int i = 0; i < materialList.size(); i++) {
								materialStrList.add(materialList.get(i).getMaterialName());
							}
						}
						// / 获取批次列表
						if (resultInfo.getMaBatchList() != null) {
							maBatchList.addAll(resultInfo.getMaBatchList());
						}
						handler.sendEmptyMessage(1);
					} else {
						Toast.makeText(NewSpectorActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			GreenhousesRequest request = (GreenhousesRequest) params[0];
			String json = Utils.toJSON(request);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(22000, true,
					json);
			// String ss = Utils.toJSON(message);
			// Log.e("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 扫码获取生产基地
	 * 
	 * @author tjh
	 */
	private class GetSCJDInfoAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
				} else {
					GreenHoseResultInfo resultInfo = (GreenHoseResultInfo) Utils.fromJSON(string,
							GreenHoseResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 2010) {
						for (int i = 0; i < greenhousesList.size(); i++) {
							if (greenhousesList.get(i).getEWM().equalsIgnoreCase(resultInfo.getGreenHoseEwm())) {
								scdySprinner.setSelection(i);
								break;
							}
						}
					}
					Toast.makeText(NewSpectorActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(2000, true,
					json);
			// String ss = Utils.toJSON(message);
			// Log.e("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 保存提交
	 * 
	 * @author tjh
	 */
	private class SaveDateAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewSpectorActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 3110) {
						NewSpectorActivity.this.finish();
					}
					Toast.makeText(NewSpectorActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			NcpRequestInfo request = (NcpRequestInfo) params[0];
			String json = Utils.toJSON(request);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(3100, true,
					json);
			// String ss = Utils.toJSON(message);
			// Log.e("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	@Override
	protected void onDestroy() {
		// 将此页面使用的其他对象消除
		super.onDestroy();
		if (ftp != null) {
			ftp = null;
		}
	}

	@Override
	public void onResume() {
		isVisible = true;
		super.onResume();
		//registerReceiver(new String[] { getString(R.string.SCAN_ACTION) });
		registerIDataReceiver(new String[] { getString(R.string.SCAN_IDATA_ACTION) });
	}

	@Override
	protected void onPause() {
		isVisible = false;
		super.onPause();
	}
	private void xiaobangScan(String resultStr){
		progressDialog = ProgressDialog.show(this, "提示", "正在提交数据....", true, false);

		CodeActivationInfo codeActivationInfo = new CodeActivationInfo();
		codeActivationInfo.setStartcode(resultStr);
		codeActivationInfo.setEnterpriseid(enterpriseid);
		codeActivationInfo.setIsnew(MyApplication.mSettings.getBoolean("isNew",false));

		GetSCJDInfoAsyn getSCJDInfoAsyn = new GetSCJDInfoAsyn();
		getSCJDInfoAsyn.execute(codeActivationInfo);
	}
	@Override
	protected void handleReceiver(Context context, Intent intent) {
		super.handleReceiver(context, intent);
		if (isVisible) {
			if (getString(R.string.SCAN_ACTION).equals(intent.getAction())) {
				String scanStatus = intent.getStringExtra(getString(R.string.SCAN_STATE));
				if ("ok".equals(scanStatus)) {
					// 成功
					String resultStr = intent.getStringExtra(getString(R.string.DATA_STRING)).trim();
					progressDialog = ProgressDialog.show(this, "提示", "正在提交数据....", true, false);

					CodeActivationInfo codeActivationInfo = new CodeActivationInfo();
					codeActivationInfo.setStartcode(resultStr);
					codeActivationInfo.setEnterpriseid(enterpriseid);
					codeActivationInfo.setIsnew(MyApplication.mSettings.getBoolean("isNew",false));

					GetSCJDInfoAsyn getSCJDInfoAsyn = new GetSCJDInfoAsyn();
					getSCJDInfoAsyn.execute(codeActivationInfo);
				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}

	@Override
	protected void handleIDataReceiver(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.handleIDataReceiver(context, intent);
		if (isVisible) {
			if (getString(R.string.SCAN_IDATA_ACTION).equals(intent.getAction())) {
				String scanResult = intent.getStringExtra("value");
				if (scanResult.length() > 0) {
					progressDialog = ProgressDialog.show(this, "提示", "正在提交数据....", true, false);

					CodeActivationInfo codeActivationInfo = new CodeActivationInfo();
					codeActivationInfo.setStartcode(scanResult);
					codeActivationInfo.setEnterpriseid(enterpriseid);
					codeActivationInfo.setIsnew(MyApplication.mSettings.getBoolean("isNew",false));

					GetSCJDInfoAsyn getSCJDInfoAsyn = new GetSCJDInfoAsyn();
					getSCJDInfoAsyn.execute(codeActivationInfo);
				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}

}